package village.rainbow.dailyscene.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import village.rainbow.dailyscene.BaseActivity;
import village.rainbow.dailyscene.Global;
import village.rainbow.dailyscene.R;
import village.rainbow.dailyscene.adapter.ViewPagerAdapter;
import village.rainbow.dailyscene.datamodel.DataRow;
import village.rainbow.dailyscene.datamodel.DataRowBean;
import village.rainbow.dailyscene.datamodel.DataTable;
import village.rainbow.dailyscene.uicontrol.SceneView;
import village.rainbow.dailyscene.util.AnimatedGifEncoder;
import village.rainbow.dailyscene.util.DateUtil;
import village.rainbow.dailyscene.util.ExifUtil;
import village.rainbow.dailyscene.util.StringUtil;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

/**
 * 사진을 찍고 메모를 남기며 
 * 일정을 정하고 알람을 설정한다.
 * 공유랑 삭제랑 수정도 되야되네 
 * @author K.O.J
 */
@SuppressLint("WorldReadableFiles")
public class SceneActivity extends BaseActivity implements OnLongClickListener{

	private Uri mCapturedImageUri;
	private int CAMERA_REQUEST = 10001;
	private int GALLERY_REQUEST = 10002;

	private final static int SAVE_MODE_SHARE 	= 1;
	private final static int SAVE_MODE_SHORCUT 	= 2;
	private final static int SAVE_MODE_SAVE 	= 3;

	private DataRow mData;

	private Button mButtonSceneDate;
	private Button mButtonAlarmTime;

	private ToggleButton mToggleGps;
	private ToggleButton mToggleShortCut;

	private ViewPager mPager;
	private ViewPagerAdapter mPagerAdapter;
	
	private ExifUtil mExifUtil;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.activity_scene);
		
		mExifUtil = new ExifUtil();
		
		TextView tvTitle = (TextView)findViewById(R.id.menu_title);
		tvTitle.setText("Make Slip");
		
		DataTable table = new DataTable();
		mPagerAdapter = new ViewPagerAdapter(this, table);

		mPager = (ViewPager)findViewById(R.id.pager);
		mPager.setAdapter(mPagerAdapter);
		mPagerAdapter.setOnClickListener(this);
		// 이거 필요한데 왜 그런지 모르겠음
		mPager.setOffscreenPageLimit(10);

		mButtonSceneDate = (Button)findViewById(R.id.btn_slip_date);
		mButtonSceneDate.setText(StringUtil.currentDate("yyyy.MM.dd (a)hh:mm"));
		mButtonSceneDate.setTypeface(Typeface.MONOSPACE);
		mButtonSceneDate.setOnClickListener(this);
		mButtonSceneDate.setTag(StringUtil.currentDate("yyyyMMddHHmmss"));
		
		mButtonAlarmTime = (Button)findViewById(R.id.btn_alarm_time);
		mButtonAlarmTime.setText("No alarm");
		mButtonAlarmTime.setOnClickListener(this);
		
		mToggleGps = (ToggleButton)findViewById(R.id.btn_toggle_gps);
		mToggleGps.setText("");
		mToggleGps.setTextOn("");
		mToggleGps.setTextOff("");
		mToggleGps.setChecked(false);
		setStateDrawable(mToggleGps);
		
		mToggleShortCut = (ToggleButton)findViewById(R.id.btn_toggle_shortcut);
		mToggleShortCut.setText("");
		mToggleShortCut.setTextOn("");
		mToggleShortCut.setTextOff("");
		mToggleShortCut.setChecked(false);
		setStateDrawable(mToggleShortCut);

		Bundle b = getIntent().getExtras();
		if(b != null && b.containsKey("DATA")){
			try{
				DataRowBean bean = (DataRowBean) b.getSerializable("DATA");
				mData = bean.getDataRow();

				table = (DataTable) mData.get("SCENE_DETAIL", new DataTable());
				mPager.setCurrentItem(mPagerAdapter.getCount()-1, false);
				mPagerAdapter.addAll(table);
				mPagerAdapter.notifyDataSetChanged();

				String alarmDate = mData.getString("ALARM_DATE", "");
				mButtonSceneDate.setText(alarmDate);
				
				String sceneDate = mData.getString("SCENE_DATE", "");
				if(sceneDate.equals("")){
					mButtonSceneDate.setTag(sceneDate);
					mButtonSceneDate.setText(DateUtil.toPatternedDate("yyyy.MM.dd (a)hh:mm", "yyyyMMddHHmmss", sceneDate));
				}
				
			}catch(Exception e){
				errorHandler(e);
			}
		}

		Button btnAdd = (Button)findViewById(R.id.btn_add);
		btnAdd.setOnClickListener(this);
		
		Button btnSave = (Button)findViewById(R.id.btn_save);
		btnSave.setOnClickListener(this);
	}
	
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	private void setStateDrawable(View buttonView){
		Drawable viewDrawable = buttonView.getBackground();
		if (viewDrawable == null)
			viewDrawable = new ColorDrawable(Color.TRANSPARENT);
		ColorDrawable wrapDrawable = new ColorDrawable(Color.parseColor("#809ec0ff"));
		Drawable[] layers = {viewDrawable, wrapDrawable};
		LayerDrawable layer = new LayerDrawable(layers);
		StateListDrawable stateDarwable = new StateListDrawable();
		stateDarwable.addState(new int[]{-android.R.attr.state_checked}, viewDrawable);
		stateDarwable.addState(new int[]{android.R.attr.state_checked}, layer);
		stateDarwable.addState(new int[]{}, viewDrawable);
		if(Build.VERSION.SDK_INT > 15){
			buttonView.setBackground(stateDarwable);	
		}else{
			buttonView.setBackgroundDrawable(stateDarwable);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mPager.invalidate();

	}

	@Override
	public void onClick(View v) {
		super.onClick(v);

		int id = v.getId();
		switch(id){
		case R.id.btn_add:
			choosePic();
			break;
		case R.id.imv_picture:
			break;
//		case R.id.btn_share:
//			save(SAVE_MODE_SHARE);
//			break;
//		case R.id.btn_shorcut:
//			save(SAVE_MODE_SHORCUT);
//			break;
		case R.id.btn_save:
			save();
			break;
//
		case R.id.btn_slip_date:
			showDateTimePicker(mButtonSceneDate);
			break;
		case R.id.btn_alarm_time:
			showAlarmPicker();
			break;
		}

	}

	private void showAlarmPicker() {
		final String[] items = new String[]{"No alarm", "5min", "10min", "15min", "30min", "1hour", "2hour", "6hour"};
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Pick Alarm time when it ringing before");
		builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				mButtonAlarmTime.setText(items[which]);
				dialog.dismiss();
			}
		});
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	private boolean mPreventDoubleClick = false;
	private void choosePic() {

		if(mPreventDoubleClick)
			return;

		mPreventDoubleClick = true;

		try{
			String[] items = {"사진 앨범", "카메라", "사진초기화"};
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("사진 선택");
			builder.setItems(items, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch(which){
					case 0:
						takePicFromGallery();
						break;
					case 1:
						takePic();
						break;
					case 2:
						dialog.dismiss();
						break;
					}
				}
			});
			AlertDialog dialog = builder.create();
			dialog.show();	

			mPreventDoubleClick = false;

		}catch(Exception e){
			errorHandler(e);
		}
	}

	protected void takePicFromGallery() {
		Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(i, GALLERY_REQUEST);
	}

	private String mImgLocation = "";

	private void takePic() {
		try {
			File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/dailyscene");
			if(!dir.exists())
				dir.mkdir();
			String imageFileName = StringUtil.currentDate("yyyyMMddHHmmss");
			File file = new File(dir, imageFileName + ".png");
			if(file.exists())
				file.delete();
			file.createNewFile();

			mImgLocation = Environment.getExternalStorageDirectory().getPath() + "/dailyscene/" + imageFileName + ".png"; 

			mCapturedImageUri = Uri.fromFile(file);

			Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			i.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageUri);
			startActivityForResult(i, CAMERA_REQUEST);
		} catch (Exception e) {
			errorHandler(e);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  
			try {
				DataRow row = new DataRow();
				row.put("SCENE_PIC_LOCATION", mImgLocation);
				mPagerAdapter.add(row);
				mPager.setCurrentItem(mPagerAdapter.getCount()-1, false);
			} catch (Exception e) {
				errorHandler(e);
			}

		}else if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();

			DataRow row = new DataRow();
			row.put("SCENE_PIC_LOCATION", picturePath);
			mPagerAdapter.add(row);
			mPager.setCurrentItem(mPagerAdapter.getCount()-1, false);
		}

	}

	private void save(){
		// 일단 로컬에 저장한다.
		try{

			if(mPagerAdapter.getCount() == 0)
				throw new Exception("내용을 입력해주시기 바랍니다.");

			String sceneInsDt = StringUtil.currentDate("yyyyMMddHHmmss");
			String firstText = "";
			Bitmap firstBitmap = null;

			DataTable sceneDetailList = new DataTable();

			int position = mPager.getCurrentItem();

			for(int i=0; i<mPager.getChildCount(); i++){
				SceneView sceneView = (SceneView)mPager.getChildAt(i);

				DataRow item = (DataRow) sceneView.getTag();
				item.put("SCENE_SORT_ORDER", i + "");
				item.put("SCENE_INS_DT", sceneInsDt);
				String sceneText = sceneView.getSceneText();
				item.put("SCENE_TEXT", sceneText);
				sceneDetailList.add(item);
				if(i == position){
					firstBitmap = BitmapFactory.decodeFile(item.getString("SCENE_PIC_LOCATION", ""));
					firstText = sceneText;
				}

			}

			String sceneDate = mButtonSceneDate.getTag().toString();
			String alarmDate = mButtonAlarmTime.getText().toString();
			if(alarmDate.startsWith("No")){
				alarmDate = "";
			}
			
			DataRow headerData = new DataRow();
			headerData.put("SCENE_INS_DT", sceneInsDt);
			headerData.put("SCENE_DATE", sceneDate);
			headerData.put("ALARM_DATE", alarmDate);
			
			String shortCutYn = mToggleShortCut.isChecked() ? "Y" : "N";
			
			String gpsUseYn = mToggleGps.isChecked() ? "Y" : "N";
			headerData.put("LOCATION_USE_YN", gpsUseYn);

			String sceneId = "";
			if(mData != null){
				sceneId = mData.getString("SCENE_ID", "");
				headerData.put("SCENE_ID", sceneId);
				mDao.updateScene(headerData, sceneDetailList);
				updateAlarm(sceneId, alarmDate, firstText);
			}else{
				sceneId = mDao.insertScene(headerData, sceneDetailList);
				updateAlarm(sceneId, alarmDate, firstText);
			}
			
			if(gpsUseYn.equals("Y")){
				mExifUtil.saveGpsData(SceneActivity.this, sceneDetailList);
			}
			
			if(shortCutYn.equals("Y")){
				getShortcutUtil().shorcutScene(firstBitmap, sceneId, firstText);
			}
			
			setResult(Activity.RESULT_OK);
			finish();
			
		}catch(Exception e){
			errorHandler(e);
		}
	}
	
	private void updateAlarm(String sceneId, String alarmDate, String sceneTxt) throws Exception {
		
		String alarmBefore = mButtonAlarmTime.getText().toString();
		if(alarmBefore.startsWith("No"))
			return;
		
		if(alarmBefore.equals("5min")){
			
		}else if(alarmBefore.equals("10min")){
			
		}else if(alarmBefore.equals("15min")){
			
		}else if(alarmBefore.equals("30min")){
			
		}else if(alarmBefore.equals("1hour")){
			
		}else if(alarmBefore.equals("2hour")){
			
		}else if(alarmBefore.equals("6hour")){
			
		}
		
		// 수정하러 들어왔는데, 알람을 해제한 경우
//		if(!mToggleAlarm.isChecked() && mData != null){
//			int sceneIdAsInteger = Integer.parseInt(mData.getString("SCENE_ID", "0"));
//			releaseAlarm(this, sceneIdAsInteger);
//		}else if(mToggleAlarm.isChecked()){
//			int sceneIdAsInteger = Integer.parseInt(sceneId);
//			long alarmT = Long.parseLong(alarmDate);
//			setAlarm(this, alarmT, sceneIdAsInteger, "Daily Scene", sceneTxt);
//		}
	}

	@Override
	public boolean onLongClick(View v) {
		int id = v.getId();
		switch(id){
		case R.id.imv_picture:
			choosePic();
			break;
		}
		return false;
	}


}
